<template>
  <div class="search-box">
    <div class="search-name">请输入密码</div>
    <div class="search-err" v-if="showErr">密码错误！请重新输入</div>
    <div class="verification-container">
      <input
        v-for="(code, index) in verificationCodes"
        v-model="verificationCodes[index]"
        @input="handleInput(index, $event)"
        @keydown="handleKeyDown(index, $event)"
        maxlength="1"
        type="password"
        class="verification-input"
      />
    </div>
  </div>
</template>

<script setup>
import { ref, nextTick } from "vue";
import { getFile } from "@/apis/template/index.js";
import { useRoute, useRouter } from "vue-router";

const route = useRoute();
const router = useRouter();
const verificationCodes = ref(["", "", "", ""]);

const showErr = ref(false);
const handleInput = (index, event) => {
  const value = event.target.value;
  verificationCodes.value[index] = value;

  // 自动跳到下一个输入框
  if (value && index < verificationCodes.value.length - 1) {
    const nextInput = event.target.nextElementSibling;
    if (nextInput) {
      nextTick(() => {
        nextInput.focus();
      });
    }
  }
  if (verificationCodes.value.join("").length === 4) {
      getFile({
        contractId: route.query.contractId,
        password: verificationCodes.value.join("")
      }).then(res => {
        if (res.code === 200) {
          router.push({
            path: "/contract-detail",
            query: { url: res.data }
          });
        }
      });

  } else {
    showErr.value = false;
  }
};
const handleKeyDown = (index, event) => {
  // 处理删除操作
  if (event.key === "Backspace" && !event.target.value && index > 0) {
    const prevInput = event.target.previousElementSibling;
    if (prevInput) {
      nextTick(() => {
        prevInput.focus();
      });
    }
  }
};
</script>

<style lang="scss" scoped>
@import "index";
</style>
